package com.mars.basic.controller;

import com.ag.exception.EntityNotFoundException;
import com.mars.basic.allmain.po.AdminUser;
import com.mars.basic.allmain.po.Picture;
import com.mars.basic.allmain.po.QPicture;
import com.mars.basic.allmain.vo.picture.PictureVo;
import com.mars.basic.service.PictureService;
import com.mars.common.utils.*;
import com.querydsl.core.types.OrderSpecifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;

@RestController
@RequestMapping("/admin/picture")
public class PictureController extends BaseController {
    @Autowired
    private PictureService pictureService;

    /**
     * 新增相册图片
     *
     * @param file
     * @param title
     * @param remark
     * @return
     */
    @RequestMapping("/addPicture")
    public R addPicture(@RequestParam("image") MultipartFile file, @RequestParam("title") String title, @RequestParam("remark") String remark) {
        AdminUser user = getSysAdminUser();
        File file1 = TenXCOS.toFile(file);
        String imgUrl = TenXCOS.upload(file1, Constants.TX_PICTURE_PATH, Constants.BUCKET_NAME_MARS);
        Picture picture = Picture.builder().createTime(new Date())
                .url(imgUrl)
                .name(file.getName())
                .remark(remark)
                .tKey(Constants.TX_FILE_PATH + file1.getName())
                .status(MarsConstant.StatusEnum.ENABLE.value())
                .updateTime(new Date())
                .userId(user.getId())
                .title(title)
                .type(MarsConstant.pictureType.ALBUM.type())
                .build();
        //删除本地图片
        file1.delete();
        pictureService.getRepo().save(picture);
        return R.ok();
    }

    /**
     * 获取图库分页
     * @param vo
     * @return
     */
    @RequestMapping("/getPage")
    public R getPicturePage(@RequestBody PictureVo vo) {
        OrderSpecifier<Date> desc = QPicture.picture.createTime.desc();
        Page<Picture> page = pictureService.getRepo().findAll(vo.where(), vo.getPageRequest(), desc);
        return R.data(page);
    }

    /**
     * 删除图片
     *
     * @return
     */
    @RequestMapping("/delPicture/{id}")
    public R deletedPicture(@PathVariable Integer id) {
        Picture picture = pictureService.getRepo().findById(id).orElse(null);
        QAssert.notNull(picture, EntityNotFoundException.class, "该图片不存在");
        TenXCOS.deletedFile(picture.getTKey(), picture.getTBucketNam());
        return R.ok();
    }
}
